package com.syx.extensiondemo.Config;

import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.transaction.RabbitTransactionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitTemplateConfig {
    //创建两个rabbitTemplate
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate=new RabbitTemplate(connectionFactory);
        return rabbitTemplate;

    }

    @Bean
    public RabbitTemplate confirmRabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate confirmRabbitTemplate=new RabbitTemplate(connectionFactory);
        confirmRabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println("执行confirm方法");
                if(ack==true){
                    System.out.println(correlationData.getId());

                }else {
                    System.out.printf("未接收到消息，原因是%s,消息id是 %s",cause,correlationData.getId());

                }
            }
        });

        //消息被退回时候的回调方法
        confirmRabbitTemplate.setMandatory(true);
        confirmRabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
            @Override
            public void returnedMessage(ReturnedMessage returned) {
                System.out.println("消息退回"+returned);
            }
        });
        return confirmRabbitTemplate;
    }


    @Bean("transRabbitTemplate")
    public RabbitTemplate transRabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate  transRabbitTemplate=new RabbitTemplate(connectionFactory);
        //设置事务为true，开启事务。
        transRabbitTemplate.setChannelTransacted(true);
        return transRabbitTemplate;

    }

    @Bean("rabbitTransactionManager")
    public RabbitTransactionManager rabbitTransactionManager(ConnectionFactory connectionFactory){
        return new RabbitTransactionManager(connectionFactory);

    }
}
